package com.godyao.framework.core.io;

import cn.hutool.core.lang.Assert;
import com.godyao.framework.utils.ClassUtils;

import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * 通过类加载器从类路径加载资源
 * @author missw
 */
public class ClassPathResource implements Resource{
    private final String path;

    private ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path, null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path, "Path must not be null");
        this.path = path;
        this.classLoader = classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader();
    }

    @Override
    public InputStream getInputStream() throws FileNotFoundException {
        InputStream inputStream = classLoader.getResourceAsStream(path);
        if (null == inputStream) {
            throw new FileNotFoundException(
                    this.path + "cannot bo found because it dose not exist"
            );
        }
        return inputStream;
    }
}
